#include <mips/regdef.h>

	.text
	.align	2
	.globl	maxHeapify
	.ent	maxHeapify

maxHeapify:
# Creacion del stack frame
	.frame		$fp, 48, ra
	.set		noreorder
	.cpload		t9
	.set		reorder
	subu		sp, sp, 48
	.cprestore	32

	sw		ra,  40(sp)
	sw		$fp, 36(sp)

	move	$fp, sp

# Guarda el parametro en el stack
	sw	a0, 48($fp)		# words
	sw	a1, 52($fp)		# i
	sw	a2, 56($fp)		# heapSize
	
	#left = 2*i
	lw		a1, 52($fp)		# i
	mul		t0, a1, 2		# 2*i
	sw		t0, 28($fp)		# left = 2*i
	
	#right = 2*i + 1
	lw		a1, 52($fp)		#i
	mul		t0, a1, 2		#2*i
	addu	t0, t0, 1		#2*i +1
	sw		t0, 24($fp)		#right = 2*i +1
	
	sw		zero, 20($fp)	# largest = 0

if_left:	
	#_if (left < heapSize && strcasecmp(words[left],words[i])>0)
	lw		t0, 28($fp)		#left
	lw		t1, 56($fp)		#heapSize
	
	bge		t0, t1, largest_i
	
	lw		t0, 28($fp)		#left	
	mul		t0, t0, 4		#[left]
	
	lw		a1, 48($fp)		#words
	addu	t0, a1, t0		#&words[left]
	lw		a0, 0(t0)		#words[left]
	
	lw		t0, 52($fp)		#i
	mul		t0, t0, 4		#[i]
	
	lw		a1, 48($fp)		#words
	addu	t0, a1, t0		#&words[i]
	lw		a1, 0(t0)		#words[i]
	
	jal		strcasecmp		#strcasecmp(words[left],words[i])
	
	bgtz	v0, largest_left	# strcasecmp(words[left],words[i]) > 0

largest_i:
	lw		t0, 52($fp)
	sw		t0, 20($fp)		#largest = i

	b		if_right

largest_left:
	lw		t0, 28($fp)		#left
	sw		t0, 20($fp)		#largest = left
	
if_right:
	#_if (right < heapSize && strcasecmp(words[right],words[largest])>0)
	lw		t0, 24($fp)		#right
	lw		t1, 56($fp)		#heapSize
	
	bge		t0, t1, if_largest
	
	lw		t0, 24($fp)		#right	
	mul		t0, t0, 4		#[right]
	
	lw		a1, 48($fp)		#words
	addu	t0, a1, t0		#&words[right]
	lw		a0, 0(t0)		#words[right]
	
	lw		t0, 20($fp)		#largest
	mul		t0, t0, 4		#[largest]
	
	lw		a1, 48($fp)		#words
	addu	t0, a1, t0		#&words[largest]
	lw		a1, 0(t0)		#words[largest]
	
	jal		strcasecmp		#strcasecmp(words[right],words[largest])
	
	blez	v0, if_largest	#strcasecmp(words[right],words[largest]) > 0
	
	lw		t0, 24($fp)		#right
	sw		t0, 20($fp)		#largest = right
	
if_largest:	
	lw		t0, 52($fp)		#i
	lw		t1, 20($fp)		#largest
	
	beq		t1, t0, fin		#largest!=i
	
swap:
	#swap(&words[i], &words[largest]);
	lw		t0, 52($fp)		#i
	mul		t0, t0, 4		#[i]

	lw		a0, 48($fp)	#&words
	addu	t0, a0, t0	#&words[i]
	
	lw		t1, 20($fp)		#largest
	mul		t1, t1, 4		#[largest]

	lw		a0, 48($fp)	#&words
	addu	t1, a0, t1	#&words[largest]

	lw		t2, 0(t0)	#words[i]
	lw		t3, 0(t1)	#words[largest]

	sw		t2, 0(t1)	# words[largest] = words[i];
	sw		t3, 0(t0)	# words[i] = words[largest]
	
	lw		a0, 48($fp)		#words
	lw		a1, 20($fp)		#largest
	lw		a2, 56($fp)		#heapSize
	
	jal		maxHeapify		#maxHeapify(words, largest, heapSize)

fin:

# Destruccion del stack frame
	move	sp, $fp
	lw		ra,  40(sp)
	lw		$fp, 36(sp)

	addiu	sp, sp, 48
	jr		ra


	.end	maxHeapify
